//
//  XLCommitRecorderView.m
//  XiangLove
//
//  Created by 宋振 on 2018/8/8.
//  Copyright © 2018年 BAOMIHUA.COM. All rights reserved.
//

#import "XLCommitRecorderView.h"
#import "XLPersonCenterTool.h"
#import "XLRecordTool.h"
#import <SVProgressHUD.h>
#import "XLVideoPlayVC.h"



@interface XLCommitRecorderView ()<UIGestureRecognizerDelegate,XLRecorderToolDelegate>

//语音显示容器
@property (nonatomic, strong) UIView *  recorderView;

//取消按钮
@property (nonatomic, strong) UIButton *  cancelButton;

//确认按钮
@property (nonatomic, strong) UIButton *  sureButton;

//语音图标背景
@property (nonatomic, strong) UIView *  recorder;

//语音图片显示
@property (nonatomic, strong) UIImageView *  recorderImg;

//语音时间容器
@property (nonatomic, strong) UIView *  recorderTimeView;

//提示语
@property (nonatomic, strong) UILabel *  titileLbl;

//读条
@property (nonatomic, strong) UIView *  progress;

//进度
@property (nonatomic, strong) CALayer *  progressLayer;

@end

@implementation XLCommitRecorderView
{
    //读取秒数
    NSInteger secondCount;
    
    //是否开始录取
    BOOL readyRecorder;
    
    //提示语
    NSString *prompt;
    
    NSLayoutConstraint *topConstraint;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    
    if (self) {
        
        //设置
        [self setMySelf];
        
        //设置语音时间标记
        [self initRecorder];
        
        //设置主要显示界面
        [self initUI];
        
        //更新主要UI动画弹出
//        [self animationView];
    }
    
    return self;
}

/**
 设置
 */
- (void)setMySelf
{
    self.backgroundColor = RGBA(0, 0, 0, 0.4);
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(leaveAction:)];
    tapGesture.numberOfTouchesRequired = 1;
    tapGesture.numberOfTapsRequired = 1;
    
    [self addGestureRecognizer:tapGesture];
    
    secondCount = 0;
    readyRecorder = NO;
    prompt = @"上滑取消";
}

#pragma mark        - - - 绘制界面显示 - - -

- (void)initUI
{
    //背景
    self.recorderView = [[UIView alloc] init];
    self.recorderView.backgroundColor = [UIColor whiteColor];
    self.recorderView.userInteractionEnabled = YES;
    [self addSubview:self.recorderView];
    
    [self.recorderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_bottom);
        make.left.right.equalTo(self);
        make.height.mas_equalTo(230);
    }];

    //语音背景
    self.recorder = [[UIView alloc] init];
    self.recorder.backgroundColor = [UIColor whiteColor];
    self.recorder.layer.cornerRadius = 55;
    self.recorder.layer.masksToBounds = YES;
    self.recorder.layer.borderWidth = 1;
    self.recorder.userInteractionEnabled = YES;
    self.recorder.layer.borderColor = RGB(230, 230, 230).CGColor;
    [self.recorderView addSubview:self.recorder];
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(startRecoredAction:)];
    longPress.numberOfTouchesRequired = 1;
    longPress.delegate = self;
    [self.recorder addGestureRecognizer:longPress];
    
    [self.recorder mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.recorderView);
        make.size.mas_equalTo(CGSizeMake(110, 110));
    }];
    
    //语音图标显示
    self.recorderImg = [[UIImageView alloc] init];
    self.recorderImg.image = [[UIImage imageNamed:@"common_icon_maikefeng"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)];
    [self.recorder addSubview:self.recorderImg];
    
    [self.recorderImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.recorder);
        make.size.mas_equalTo(CGSizeMake(45, 45));
    }];
    
    //设置取消按钮
    self.cancelButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.cancelButton.frame = CGRectMake(0, 0, 32, 32);
    self.cancelButton.hidden = YES;
    [self layOutButton:self.cancelButton withImage:@"recorderChacha"];
    [self.cancelButton addTarget:self action:@selector(cancelAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.recorderView addSubview:self.cancelButton];
    
    [self.cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.recorderView.mas_centerY);
        make.left.equalTo(self.recorderView.mas_left).offset(52);
        make.size.mas_equalTo(CGSizeMake(32, 32));
    }];
    
    //设置完成按钮
    self.sureButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.sureButton.frame = CGRectMake(0, 0, 32, 32);
    self.sureButton.hidden = YES;
    [self layOutButton:self.sureButton withImage:@"select"];
    [self.sureButton addTarget:self action:@selector(sureAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.recorderView addSubview:self.sureButton];
    
    [self.sureButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.recorderView.mas_centerY);
        make.right.equalTo(self.recorderView.mas_right).offset(-52);
        make.size.mas_equalTo(CGSizeMake(32, 32));
    }];
    
    [self.recorderView layoutIfNeeded];
    [self layoutIfNeeded];
}

#pragma mark        - - - 显示语音时间等 - - -
- (void)initRecorder
{
    self.recorderTimeView = [[UIView alloc] init];
    self.recorderTimeView.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.recorderTimeView];
    
    [self.recorderTimeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_bottom);
        make.left.right.equalTo(self);
        make.height.mas_equalTo(44);
    }];
    
    //上滑取消 松手取消
    self.titileLbl = [[UILabel alloc] init];
    self.titileLbl.textAlignment = NSTextAlignmentCenter;
    self.titileLbl.attributedText = [self setTitleAttributeText:@"上滑取消" timeText:@"0"];
    [self.recorderTimeView addSubview:self.titileLbl];
    
    [self.titileLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.recorderTimeView.mas_centerY);
        make.left.equalTo(self.recorderTimeView.mas_left).offset(20);
        make.right.equalTo(self.recorderTimeView.mas_right).offset(-20);
    }];
    //
    self.progress = [[UIView alloc] init];
    self.progress.backgroundColor = RGB(230, 230, 230);
    [self.recorderTimeView addSubview:self.progress];
    
    [self.progress mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.recorderTimeView);
        make.bottom.equalTo(self.recorderTimeView.mas_bottom).offset(-1);
        make.height.mas_equalTo(1);
    }];
    
    //进度
    self.progressLayer = [CALayer layer];
    
    self.progressLayer.backgroundColor = RGB(255, 187, 1).CGColor;
    
    self.progressLayer.frame = CGRectMake(0, 0, 0, 1.5);
    
    [self.progress.layer addSublayer:self.progressLayer];
    
}

#pragma mark        - - - 动画弹出界面 - - -
- (void)animationView
{
    if (self.recorderView && self.recorderTimeView) {
        
        [self.recorderView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.mas_bottom).offset(-230);

        }];
        
        [self.recorderTimeView mas_updateConstraints:^(MASConstraintMaker *make) {

            make.top.equalTo(self.recorderView.mas_top);

        }];
        
        [UIView animateWithDuration:0.5 animations:^{
            
            [self.recorderView.superview layoutIfNeeded];
        }];
        
    }
}


#pragma mark        - - - Tools - - -

//更新提示界面显示 (上弹)
- (void)updateRecorderTitleViewTop
{
    [self.recorderTimeView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self);
        make.top.equalTo(self.recorderView.mas_top).offset(-44);
        make.height.mas_equalTo(44);
    }];
    
    [UIView animateWithDuration:0.3 animations:^{
        
        [self layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
}
//更新提示界面显示 (下隐)
- (void)updateRecorderTitleViewBottom
{
    [self.recorderTimeView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self);
        make.top.equalTo(self.recorderView.mas_top);
        make.height.mas_equalTo(44);
    }];
    
    [UIView animateWithDuration:0.3 animations:^{
        [self layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
}

//录音成功隐藏显示
- (void)setRecorderAnimationViewHidden
{
    //首先隐藏录音界面
    [self.recorderTimeView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self);
        make.top.equalTo(self.mas_bottom);
        make.height.mas_equalTo(44);
    }];
    
    [self.recorderView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_bottom).offset(0);
        make.left.right.equalTo(self);
        make.height.mas_equalTo(230);
    }];
    
    [UIView animateWithDuration:0.3 animations:^{
        [self layoutIfNeeded];
    } completion:^(BOOL finished) {
        
        if (finished) {
            
            //动画结束上传录音文件
            NSString *urlString = [[XLRecordTool shareRecordTool] getRecorderUrl];
            
            if (urlString) {
                
                if (self.delegate && [_delegate respondsToSelector:@selector(commitRecorderClickSuccessRecorderWithUrl:andTimeSecond:)]) {

                    self.cancelButton.hidden = YES;
                    self.sureButton.hidden = YES;
                    
                    [self.delegate commitRecorderClickSuccessRecorderWithUrl:urlString andTimeSecond:secondCount];
                }
                
            }
            
            //防止位置有问题
            [self animationView];

        }
        
    }];
}

//设置取消完成按钮
- (void)layOutButton:(UIButton *)button withImage:(NSString *)imageName
{
    button.layer.cornerRadius = 16;
    button.layer.masksToBounds = YES;
    [button setImage:[[UIImage imageNamed:imageName] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] forState:(UIControlStateNormal)];
}

//设置提示字体颜色
- (NSMutableAttributedString *)setTitleAttributeText:(NSString *)text timeText:(NSString *)timeText
{
    NSMutableAttributedString *muAttributeText = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ (%@”)",text,timeText]];
    
    //提示
    NSRange textRangeOne = [[muAttributeText string] rangeOfString:text];
    
    //时间
    NSRange textRangeTwo = [[muAttributeText string] rangeOfString:[NSString stringWithFormat:@"(%@”)",timeText]];
    
    [muAttributeText addAttributes:@{
                                     NSFontAttributeName:[UIFont fontWithName:KFontNamePFMedium size:15],
                                     NSForegroundColorAttributeName:RGB(153, 153, 153)
                                     } range:textRangeOne];
    [muAttributeText addAttributes:@{
                                     NSFontAttributeName:[UIFont fontWithName:KFontNamePFMedium size:15],
                                     NSForegroundColorAttributeName:RGB(255, 187, 1)
                                     } range:textRangeTwo];
    
    return muAttributeText;
}

/**
 是否在指定位置上
 */
- (BOOL)localWithCenter:(CGPoint)center
{
    NSString *timeSecond = [NSString stringWithFormat:@"%ld",secondCount];
    
    if (center.y < self.recorder.frame.origin.y-60) {
        
        self.titileLbl.attributedText = [self setTitleAttributeText:@"松开取消" timeText:timeSecond];
        
        prompt = @"松开取消";
        
        return YES;
        
    }else{
        self.titileLbl.attributedText = [self setTitleAttributeText:@"上滑取消" timeText:timeSecond];
        
        prompt = @"上滑取消";
        
        return NO;
    }
    
    
    return YES;
}

/**
 设置进度
 */
- (void)setProgressWidth:(CGFloat)width
{
    self.progressLayer.frame = CGRectMake(0, 0, width, 1.5);
}


#pragma mark        - - - Action - - -

/**
 取消录音
 */
- (void)cancelAction
{
    NSLog(@"点击取消");
    
    //防止出现意外 先停止录音
    [[XLRecordTool shareRecordTool] stopRecord];
    
    //销毁录音文件
    [[XLRecordTool shareRecordTool] destroyRecord];
    
    //隐藏控件
    self.cancelButton.hidden = YES;
    self.sureButton.hidden = YES;
    
    //清空进度
    [self setProgressWidth:0];
    
    //隐藏提示显示界面
    [self updateRecorderTitleViewBottom];
}

/**
 完成录音
 */
- (void)sureAction
{
    NSLog(@"完成录音,上传文件");
    
    [self setRecorderAnimationViewHidden];
    
}

/**
 取消界面
 */
- (void)leaveAction:(UITapGestureRecognizer *)sender
{
    
    CGPoint point = [sender locationInView:self];
    
    CGFloat height = kScreenH - 230;
    
    if (point.y < height) {
        
        //首先隐藏录音界面
        [self.recorderTimeView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self);
            make.top.equalTo(self.mas_bottom);
            make.height.mas_equalTo(44);
        }];
        
        [self.recorderView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.mas_bottom).offset(0);
            make.left.right.equalTo(self);
            make.height.mas_equalTo(230);
        }];
        
        [UIView animateWithDuration:0.5 animations:^{
            
            [self layoutIfNeeded];
            
        } completion:^(BOOL finished) {
            
            if (self.delegate && [_delegate respondsToSelector:@selector(commitRecorderClickDestroyView)]) {
                [self.delegate commitRecorderClickDestroyView];
            }
            
        }];
        
        
        
    }
    
}

/**
 长按录音
 */
- (void)startRecoredAction:(UILongPressGestureRecognizer *)sender
{
    
    NSLog(@"长按录音");
    
    //是否可以松开取消
    BOOL isCancel = NO;
    
    //录音回调代理信息
    [XLRecordTool shareRecordTool].delegate = self;
    
    switch (sender.state) {
        case UIGestureRecognizerStateBegan:
        {
            [self layoutIfNeeded];
            
            //录音准备
            [self recorderReady];
            NSLog(@"Began");
            
            break;
        }
        case UIGestureRecognizerStateFailed:
        {
            NSLog(@"Failed");
            
            break;
        }
        case UIGestureRecognizerStateChanged:
        {
            NSLog(@"change");
            //是否在指定视图上
            CGPoint local = [sender locationInView:self.recorderView];
            isCancel = [self localWithCenter:local];
            
            break;
        }
        case UIGestureRecognizerStateEnded:
        {
            //低于十秒
            if (secondCount < 10) {
                
                [MBProgressHUD showContent:@"录音少于10秒"];;
                
                //隐藏提示显示界面
                [self updateRecorderTitleViewBottom];
            }else{
                self.cancelButton.hidden = NO;
                self.sureButton.hidden = NO;
            }
            
            [self endRecorder];
            
            break;
        }
            
            
        default:
            
            NSLog(@"default");
            
            //如果松开取消 （未发现安卓方面有何不同）
            if (isCancel) {
                
                
            }else{
                //如果手势未超出指定距离
                
            }
            
            //低于十秒
            if (secondCount < 10) {
                [MBProgressHUD showContent:@"录音少于10秒"];;
                
                //隐藏提示显示界面
                [self updateRecorderTitleViewBottom];
            }else{
                self.cancelButton.hidden = NO;
                self.sureButton.hidden = NO;
            }
            
            [self endRecorder];
            
            
            break;
    }
    
    
}

//准备录音
- (void)recorderReady
{
    prompt = @"上滑取消";
    
    //隐藏标志
    self.recorderImg.hidden = YES;
    
    //更新背景颜色
    self.recorder.backgroundColor = RGB(230, 230, 230);
    
    //防止录音未停止
    if (readyRecorder) {
        //录音准备
        [[XLRecordTool shareRecordTool] stopRecord];

    }
    //录音准备
    [[XLRecordTool shareRecordTool] startRecord];
    [[XLRecordTool shareRecordTool] destroyRecord];
    readyRecorder = YES;
    
    //更新进度准备
    self.progressLayer.frame = CGRectMake(0, 0, 0, 1.5);
    
    //更新秒数准备
    self.titileLbl.attributedText = [self setTitleAttributeText:@"上滑取消" timeText:[NSString stringWithFormat:@"%d",0]];
    
    //显示提示界面和进度
    [self updateRecorderTitleViewTop];
    
}

//结束录音
- (void)endRecorder
{
    //更新背景颜色
    self.recorder.backgroundColor = [UIColor whiteColor];
    
    //显示标志
    self.recorderImg.hidden = NO;
    
    //停止录音
    [[XLRecordTool shareRecordTool] stopRecord];
    
    //停止状态
    readyRecorder = NO;
}



#pragma mark        - - - 手势代理 - - -
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRequireFailureOfGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return NO;
}

#pragma mark        - - - 方法代理 - - -
- (void)updateTime:(NSInteger)second
{
    secondCount = second;
    
    //更新进度 最多15秒 获取每秒所要走的宽度
    CGFloat parkProgress = ScreenWidth/15;
    
    //计算当前需要绘制的宽度
    CGFloat width = parkProgress * second;
    
    //更新进度显示
    self.progressLayer.frame = CGRectMake(0, 0, width, 1.5);
    
    self.titileLbl.attributedText = [self setTitleAttributeText:prompt timeText:[NSString stringWithFormat:@"%ld",second]];
    
    prompt = @"松开取消";
    
    //超过15秒 就停止录音
    if (second >= 15) {
        
        self.cancelButton.hidden = NO;
        self.sureButton.hidden = NO;
        [self endRecorder];
        
    }
    
}





@end
